<?php
declare(strict_types=1);

namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\facade\Request;
use think\facade\Validate;

/**
 * 财务模块控制器
 */
class Finance extends BaseController
{
    /**
     * 获取应收款项列表
     */
    public function getReceivableList()
    {
        $pageNo = (int)Request::param('pageNo', 1);
        $pageSize = (int)Request::param('pageSize', 10);
        $customer_name = Request::param('customer_name', '');
        $status = Request::param('status', '');
        
        // 打印接收到的参数，便于调试
        trace("接收到的参数: pageNo={$pageNo}, pageSize={$pageSize}, customer_name={$customer_name}, status={$status}", 'info');
        
        $where = [];
        if (!empty($customer_name)) {
            $customerIds = Db::name('customer')
                ->where('customer_name', 'like', "%{$customer_name}%")
                ->column('id');
            if (!empty($customerIds)) {
                $where[] = ['customer_id', 'in', $customerIds];
            } else {
                // 如果没有匹配的客户，返回空结果
                return json(['code' => 200, 'msg' => '获取成功', 'data' => ['list' => [], 'total' => 0]]);
            }
        }
        
        if ($status !== '') {
            $where[] = ['status', '=', (int)$status];
        }
        
        $total = Db::name('finance_receivable')->where($where)->count();
        $list = Db::name('finance_receivable')
            ->where($where)
            ->page($pageNo, $pageSize)
            ->order('id', 'desc')
            ->select()
            ->toArray();
            
        // 关联客户信息
        foreach ($list as &$item) {
            $customer = Db::name('customer')->where('id', $item['customer_id'])->find();
            $item['customer_name'] = $customer ? $customer['customer_name'] : '';
        }
        
        // 打印返回的数据，便于调试
        trace("返回数据: total={$total}, list_count=".count($list), 'info');
        
        // 检查数据库中是否有数据
        $allRecords = Db::name('finance_receivable')->count();
        trace("数据库中总记录数: {$allRecords}", 'info');
        
        if (empty($list) && $allRecords > 0) {
            // 如果没有数据但数据库中有记录，返回第一页数据
            $list = Db::name('finance_receivable')
                ->page(1, $pageSize)
                ->order('id', 'desc')
                ->select()
                ->toArray();
                
            // 关联客户信息
            foreach ($list as &$item) {
                $customer = Db::name('customer')->where('id', $item['customer_id'])->find();
                $item['customer_name'] = $customer ? $customer['customer_name'] : '';
            }
            
            trace("返回第一页数据: count=".count($list), 'info');
            return json(['code' => 200, 'msg' => '获取成功', 'data' => ['list' => $list, 'total' => $allRecords]]);
        }
        
        return json(['code' => 200, 'msg' => '获取成功', 'data' => ['list' => $list, 'total' => $total]]);
    }
    
    /**
     * 添加应收款项
     */
    public function addReceivable()
    {
        $data = Request::post();
        
        $validate = Validate::rule([
            'customer_id' => 'require|number',
            'amount' => 'require|float',
            'due_date' => 'require|date',
            'status' => 'require|number',
        ]);
        
        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }
        
        // 只保留数据库中存在的字段
        $saveData = [
            'customer_id' => $data['customer_id'],
            'amount' => $data['amount'],
            'due_date' => $data['due_date'],
            'status' => $data['status'],
            'create_time' => date('Y-m-d H:i:s')
        ];
        
        // 如果有备注，也保存
        if (isset($data['remark'])) {
            $saveData['remark'] = $data['remark'];
        }
        
        $result = Db::name('finance_receivable')->insert($saveData);
        
        if ($result) {
            return json(['code' => 200, 'msg' => '添加成功']);
        } else {
            return json(['code' => 400, 'msg' => '添加失败']);
        }
    }
    
    /**
     * 更新应收款项
     */
    public function updateReceivable()
    {
        $data = Request::post();
        
        $validate = Validate::rule([
            'id' => 'require|number',
            'customer_id' => 'require|number',
            'amount' => 'require|float',
            'due_date' => 'require|date',
            'status' => 'require|number',
        ]);
        
        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }
        
        // 只保留数据库中存在的字段
        $saveData = [
            'id' => $data['id'],
            'customer_id' => $data['customer_id'],
            'amount' => $data['amount'],
            'due_date' => $data['due_date'],
            'status' => $data['status'],
            'update_time' => date('Y-m-d H:i:s')
        ];
        
        // 如果有备注，也保存
        if (isset($data['remark'])) {
            $saveData['remark'] = $data['remark'];
        }
        
        $result = Db::name('finance_receivable')->update($saveData);
        
        if ($result !== false) {
            return json(['code' => 200, 'msg' => '更新成功']);
        } else {
            return json(['code' => 400, 'msg' => '更新失败']);
        }
    }
    
    /**
     * 删除应收款项
     */
    public function deleteReceivable()
    {
        $id = Request::param('id');
        $ids = Request::param('ids');
        
        if (empty($id) && empty($ids)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        // 批量删除
        if (!empty($ids)) {
            // 如果ids是字符串，将其转换为数组
            if (is_string($ids)) {
                $ids = explode(',', $ids);
            }
            
            $result = Db::name('finance_receivable')->delete($ids);
        } else {
            // 单个删除
        $result = Db::name('finance_receivable')->delete($id);
        }
        
        if ($result) {
            return json(['code' => 200, 'msg' => '删除成功']);
        } else {
            return json(['code' => 400, 'msg' => '删除失败']);
        }
    }

     /**
     * 获取应付款项列表
     */
    public function getPayableList()
    {
        $pageNo = (int)Request::param('pageNo', 1);
        $pageSize = (int)Request::param('pageSize', 10);
        $supplier_name = Request::param('supplier_name', '');
        $status = Request::param('status', '');
        
        $where = [];
        if (!empty($supplier_name)) {
            $supplierIds = Db::name('supplier')
                ->where('supplier_name', 'like', "%{$supplier_name}%")
                ->column('id');
            if (!empty($supplierIds)) {
                $where[] = ['supplier_id', 'in', $supplierIds];
            } else {
                // 如果没有匹配的供应商，返回空结果
                return json(['code' => 200, 'msg' => '获取成功', 'data' => ['list' => [], 'total' => 0]]);
            }
        }
        
        if ($status !== '') {
            $where[] = ['status', '=', (int)$status];
        }
        
        $total = Db::name('finance_payable')->where($where)->count();
        $list = Db::name('finance_payable')
            ->where($where)
            ->page($pageNo, $pageSize)
            ->order('id', 'desc')
            ->select()
            ->toArray();
            
        // 关联供应商信息
        foreach ($list as &$item) {
            $supplier = Db::name('supplier')->where('id', $item['supplier_id'])->find();
            $item['supplier_name'] = $supplier ? $supplier['supplier_name'] : '';
        }
        
        // 记录日志
        file_put_contents(__DIR__ . '/log250825/payable_list.log', date('Y-m-d H:i:s') . ' - 查询应付款项列表: ' . json_encode([
            'params' => ['pageNo' => $pageNo, 'pageSize' => $pageSize, 'supplier_name' => $supplier_name, 'status' => $status],
            'count' => $total,
            'list_count' => count($list)
        ], JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
        
        return json(['code' => 200, 'msg' => '获取成功', 'data' => ['list' => $list, 'total' => $total]]);
    }
    
    /**
     * 添加应付款项
     */
    public function addPayable()
    {
        $data = Request::post();
        
        $validate = Validate::rule([
            'supplier_id' => 'require|number',
            'amount' => 'require|float',
            'due_date' => 'require|date',
            'status' => 'require|number',
        ]);
        
        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }
        
        // 过滤掉不存在的字段
        $allowedFields = [
            'supplier_id', 'amount', 'due_date', 'status', 'remark', 'create_time'
        ];
        
        $filteredData = [];
        foreach ($allowedFields as $field) {
            if (isset($data[$field])) {
                $filteredData[$field] = $data[$field];
            }
        }
        
        $filteredData['create_time'] = date('Y-m-d H:i:s');
        
        // 记录日志
        file_put_contents(__DIR__ . '/log250825/payable_add.log', date('Y-m-d H:i:s') . ' - 添加应付款项: ' . json_encode($filteredData, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
        
        $id = Db::name('finance_payable')->insertGetId($filteredData);
        
        if ($id) {
            // 获取新增的应付款项
            $newPayable = Db::name('finance_payable')->where('id', $id)->find();
            
            // 关联供应商信息
            $supplier = Db::name('supplier')->where('id', $newPayable['supplier_id'])->find();
            $newPayable['supplier_name'] = $supplier ? $supplier['supplier_name'] : '';
            
            return json(['code' => 200, 'msg' => '添加成功', 'data' => $newPayable]);
        } else {
            return json(['code' => 400, 'msg' => '添加失败']);
        }
    }
    
    /**
     * 更新应付款项
     */
    public function updatePayable()
    {
        $data = Request::post();
        
        $validate = Validate::rule([
            'id' => 'require|number',
            'supplier_id' => 'require|number',
            'amount' => 'require|float',
            'due_date' => 'require|date',
            'status' => 'require|number',
        ]);
        
        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }
        
        // 过滤掉不存在的字段
        $allowedFields = [
            'id', 'supplier_id', 'amount', 'due_date', 'status', 'remark', 'update_time'
        ];
        
        $filteredData = [];
        foreach ($allowedFields as $field) {
            if (isset($data[$field])) {
                $filteredData[$field] = $data[$field];
            }
        }
        
        $filteredData['update_time'] = date('Y-m-d H:i:s');
        
        // 记录日志
        file_put_contents(__DIR__ . '/log250825/payable_update.log', date('Y-m-d H:i:s') . ' - 更新应付款项: ' . json_encode($filteredData, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
        
        $result = Db::name('finance_payable')->update($filteredData);
        
        if ($result !== false) {
            // 获取更新后的应付款项
            $updatedPayable = Db::name('finance_payable')->where('id', $filteredData['id'])->find();
            
            // 关联供应商信息
            $supplier = Db::name('supplier')->where('id', $updatedPayable['supplier_id'])->find();
            $updatedPayable['supplier_name'] = $supplier ? $supplier['supplier_name'] : '';
            
            return json(['code' => 200, 'msg' => '更新成功', 'data' => $updatedPayable]);
        } else {
            return json(['code' => 400, 'msg' => '更新失败']);
        }
    }
    
    /**
     * 删除应付款项
     */
    public function deletePayable()
    {
        $id = Request::param('id');
        $ids = Request::param('ids');
        
        if (empty($id) && empty($ids)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        // 记录日志
        file_put_contents(__DIR__ . '/log250825/payable_delete.log', date('Y-m-d H:i:s') . ' - 删除应付款项: ' . json_encode([
            'id' => $id,
            'ids' => $ids
        ], JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
        
        // 批量删除
        if (!empty($ids)) {
            // 如果ids是字符串，将其转换为数组
            if (is_string($ids)) {
                $ids = explode(',', $ids);
            }
            
            $result = Db::name('finance_payable')->delete($ids);
        } else {
            // 单个删除
            $result = Db::name('finance_payable')->delete($id);
        }
        
        if ($result) {
            return json(['code' => 200, 'msg' => '删除成功']);
        } else {
            return json(['code' => 400, 'msg' => '删除失败']);
        }
    }

        /**
     * 获取收款单列表
     */
    public function getReceiptList()
    {
        $pageNo = Request::param('pageNo', 1);
        $pageSize = Request::param('pageSize', 10);
        $customer_name = Request::param('customer_name', '');
        $receipt_no = Request::param('receipt_no', '');
        $status = Request::param('status', '');
        
        $where = [];
        if (!empty($customer_name)) {
            $customerIds = Db::name('customer')
                ->where('customer_name', 'like', "%{$customer_name}%")
                ->column('id');
            if (!empty($customerIds)) {
                $where[] = ['customer_id', 'in', $customerIds];
            }
        }
        
        if (!empty($receipt_no)) {
            $where[] = ['receipt_no', 'like', "%{$receipt_no}%"];
        }
        
        if ($status !== '') {
            $where[] = ['status', '=', (int)$status];
        }
        
        $total = Db::name('finance_receipt')->where($where)->count();
        $list = Db::name('finance_receipt')
            ->where($where)
            ->page((int)$pageNo, (int)$pageSize)
            ->order('id', 'desc')
            ->select()
            ->toArray();
            
        // 关联客户信息
        foreach ($list as &$item) {
            $customer = Db::name('customer')->where('id', $item['customer_id'])->find();
            $item['customer_name'] = $customer ? $customer['customer_name'] : '';
        }
        
        return json([
            'code' => 200, 
            'msg' => '获取成功', 
            'data' => [
                'list' => $list,
                'total' => $total
            ]
        ]);
    }
    
    /**
     * 添加收款单
     */
    public function addReceipt()
    {
        $data = Request::post();
        
        $validate = Validate::rule([
            'customer_id' => 'require|number',
            'amount' => 'require|float',
            'receipt_date' => 'require|date',
            'receipt_type' => 'require',
            'status' => 'require|number',
        ]);
        
        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }
        
        // 过滤掉不存在的字段
        $allowedFields = [
            'customer_id', 'amount', 'receipt_date', 'receipt_type', 'status', 'remark', 'receipt_no', 'create_time'
        ];
        
        $filteredData = [];
        foreach ($allowedFields as $field) {
            if (isset($data[$field])) {
                $filteredData[$field] = $data[$field];
            }
        }
        
        // 生成收款单号
        $filteredData['receipt_no'] = 'SKD' . date('YmdHis') . rand(1000, 9999);
        $filteredData['create_time'] = date('Y-m-d H:i:s');
        
        // 记录日志
        file_put_contents(__DIR__ . '/log250825/receipt_add.log', date('Y-m-d H:i:s') . ' - 添加收款单: ' . json_encode($filteredData, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
        
        $result = Db::name('finance_receipt')->insert($filteredData);
        
        if ($result) {
            return json(['code' => 200, 'msg' => '添加成功']);
        } else {
            return json(['code' => 400, 'msg' => '添加失败']);
        }
    }
    
    /**
     * 更新收款单
     */
    public function updateReceipt()
    {
        $data = Request::post();
        
        $validate = Validate::rule([
            'id' => 'require|number',
            'customer_id' => 'require|number',
            'amount' => 'require|float',
            'receipt_date' => 'require|date',
            'receipt_type' => 'require',
            'status' => 'require|number',
        ]);
        
        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }
        
        // 过滤掉不存在的字段
        $allowedFields = [
            'id', 'customer_id', 'amount', 'receipt_date', 'receipt_type', 'status', 'remark', 'update_time'
        ];
        
        $filteredData = [];
        foreach ($allowedFields as $field) {
            if (isset($data[$field])) {
                $filteredData[$field] = $data[$field];
            }
        }
        
        $filteredData['update_time'] = date('Y-m-d H:i:s');
        
        // 记录日志
        file_put_contents(__DIR__ . '/log250825/receipt_update.log', date('Y-m-d H:i:s') . ' - 更新收款单: ' . json_encode($filteredData, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
        
        $result = Db::name('finance_receipt')->update($filteredData);
        
        if ($result !== false) {
            return json(['code' => 200, 'msg' => '更新成功']);
        } else {
            return json(['code' => 400, 'msg' => '更新失败']);
        }
    }
    
    /**
     * 删除收款单
     */
    public function deleteReceipt()
    {
        $id = Request::param('id');
        $ids = Request::param('ids');
        
        if (empty($id) && empty($ids)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        // 批量删除
        if (!empty($ids)) {
            // 如果ids是字符串，将其转换为数组
            if (is_string($ids)) {
                $ids = explode(',', $ids);
            }
            
            $result = Db::name('finance_receipt')->delete($ids);
        } else {
            // 单个删除
            $result = Db::name('finance_receipt')->delete($id);
        }
        
        if ($result) {
            return json(['code' => 200, 'msg' => '删除成功']);
        } else {
            return json(['code' => 400, 'msg' => '删除失败']);
        }
    }

        /**
     * 获取付款单列表
     */
    public function getPaymentList()
    {
        $pageNo = Request::param('pageNo', 1);
        $pageSize = Request::param('pageSize', 10);
        $supplier_name = Request::param('supplier_name', '');
        $payment_no = Request::param('payment_no', '');
        $status = Request::param('status', '');
        
        $where = [];
        if (!empty($supplier_name)) {
            $supplierIds = Db::name('supplier')
                ->where('supplier_name', 'like', "%{$supplier_name}%")
                ->column('id');
            if (!empty($supplierIds)) {
                $where[] = ['supplier_id', 'in', $supplierIds];
            }
        }
        
        if (!empty($payment_no)) {
            $where[] = ['payment_no', 'like', "%{$payment_no}%"];
        }
        
        if ($status !== '') {
            $where[] = ['status', '=', (int)$status];
        }
        
        $total = Db::name('finance_payment')->where($where)->count();
        $list = Db::name('finance_payment')
            ->where($where)
            ->page((int)$pageNo, (int)$pageSize)
            ->order('id', 'desc')
            ->select()
            ->toArray();
            
        // 关联供应商信息
        foreach ($list as &$item) {
            $supplier = Db::name('supplier')->where('id', $item['supplier_id'])->find();
            $item['supplier_name'] = $supplier ? $supplier['supplier_name'] : '';
        }
        
        return json([
            'code' => 200, 
            'msg' => '获取成功', 
            'data' => [
                'list' => $list,
                'total' => $total
            ]
        ]);
    }
    
    /**
     * 添加付款单
     */
    public function addPayment()
    {
        $data = Request::post();
        
        $validate = Validate::rule([
            'supplier_id' => 'require|number',
            'amount' => 'require|float',
            'payment_date' => 'require|date',
            'payment_type' => 'require',
            'status' => 'require|number',
        ]);
        
        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }
        
        // 过滤掉不存在的字段
        $allowedFields = [
            'supplier_id', 'amount', 'payment_date', 'payment_type', 'status', 'remark', 'payment_no', 'create_time'
        ];
        
        $filteredData = [];
        foreach ($allowedFields as $field) {
            if (isset($data[$field])) {
                $filteredData[$field] = $data[$field];
            }
        }
        
        // 生成付款单号
        $filteredData['payment_no'] = 'FKD' . date('YmdHis') . rand(1000, 9999);
        $filteredData['create_time'] = date('Y-m-d H:i:s');
        
        // 记录日志
        file_put_contents(__DIR__ . '/log250825/payment_add.log', date('Y-m-d H:i:s') . ' - 添加付款单: ' . json_encode($filteredData, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
        
        $result = Db::name('finance_payment')->insert($filteredData);
        
        if ($result) {
            return json(['code' => 200, 'msg' => '添加成功']);
        } else {
            return json(['code' => 400, 'msg' => '添加失败']);
        }
    }
    
    /**
     * 更新付款单
     */
    public function updatePayment()
    {
        $data = Request::post();
        
        $validate = Validate::rule([
            'id' => 'require|number',
            'supplier_id' => 'require|number',
            'amount' => 'require|float',
            'payment_date' => 'require|date',
            'payment_type' => 'require',
            'status' => 'require|number',
        ]);
        
        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }
        
        // 过滤掉不存在的字段
        $allowedFields = [
            'id', 'supplier_id', 'amount', 'payment_date', 'payment_type', 'status', 'remark', 'update_time'
        ];
        
        $filteredData = [];
        foreach ($allowedFields as $field) {
            if (isset($data[$field])) {
                $filteredData[$field] = $data[$field];
            }
        }
        
        $filteredData['update_time'] = date('Y-m-d H:i:s');
        
        // 记录日志
        file_put_contents(__DIR__ . '/log250825/payment_update.log', date('Y-m-d H:i:s') . ' - 更新付款单: ' . json_encode($filteredData, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
        
        $result = Db::name('finance_payment')->update($filteredData);
        
        if ($result !== false) {
            return json(['code' => 200, 'msg' => '更新成功']);
        } else {
            return json(['code' => 400, 'msg' => '更新失败']);
        }
    }
    
    /**
     * 删除付款单
     */
    public function deletePayment()
    {
        $id = Request::param('id');
        $ids = Request::param('ids');
        
        if (empty($id) && empty($ids)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        // 批量删除
        if (!empty($ids)) {
            // 如果ids是字符串，将其转换为数组
            if (is_string($ids)) {
                $ids = explode(',', $ids);
            }
            
            $result = Db::name('finance_payment')->delete($ids);
        } else {
            // 单个删除
            $result = Db::name('finance_payment')->delete($id);
        }
        
        if ($result) {
            return json(['code' => 200, 'msg' => '删除成功']);
        } else {
            return json(['code' => 400, 'msg' => '删除失败']);
        }
    }

    /**
     * 获取费用报销列表
     */
    public function getExpenseList()
    {
        $pageNo = (int)Request::param('pageNo', 1);
        $pageSize = (int)Request::param('pageSize', 10);
        $employee_name = Request::param('employee_name', '');
        $status = Request::param('status', '');
        
        $where = [];
        if (!empty($employee_name)) {
            $userIds = Db::name('user')
                ->where('realname', 'like', "%{$employee_name}%")
                ->column('id');
            if (!empty($userIds)) {
                $where[] = ['user_id', 'in', $userIds];
            } else {
                // 如果没有匹配的用户，返回空结果
                return json(['code' => 200, 'msg' => '获取成功', 'data' => ['list' => [], 'total' => 0]]);
            }
        }
        
        if ($status !== '') {
            $where[] = ['status', '=', (int)$status];
        }
        
        $total = Db::name('finance_expense')->where($where)->count();
        $list = Db::name('finance_expense')
            ->where($where)
            ->page($pageNo, $pageSize)
            ->order('id', 'desc')
            ->select()
            ->toArray();
            
        // 关联用户和部门信息
        foreach ($list as &$item) {
            $user = Db::name('user')->where('id', $item['user_id'])->find();
            $department = Db::name('user_department')->where('id', $item['department_id'])->find();
            $item['employee_name'] = $user ? $user['realname'] : '';
            $item['department_name'] = $department ? $department['name'] : '';
            
            // 将user_id映射为employee_id（前端需要）
            $item['employee_id'] = $item['user_id'];
        }
        
        // 记录日志
        file_put_contents(__DIR__ . '/log250825/expense_list.log', date('Y-m-d H:i:s') . ' - 查询费用报销列表: ' . json_encode([
            'params' => ['pageNo' => $pageNo, 'pageSize' => $pageSize, 'employee_name' => $employee_name, 'status' => $status],
            'count' => $total,
            'list_count' => count($list)
        ], JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
        
        return json(['code' => 200, 'msg' => '获取成功', 'data' => ['list' => $list, 'total' => $total]]);
    }
    
    /**
     * 添加费用报销
     */
    public function addExpense()
    {
        $data = Request::post();
        
        // 记录原始请求数据
        file_put_contents(__DIR__ . '/log250825/expense_raw_data.log', date('Y-m-d H:i:s') . ' - 原始请求数据: ' . json_encode($data, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
        
        $validate = Validate::rule([
            'employee_id' => 'require|number',
            'expense_type' => 'require',
            'amount' => 'require|float',
            'expense_date' => 'require|date',
            'status' => 'require|number',
        ]);
        
        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }
        
        // 将employee_id映射到user_id
        if (isset($data['employee_id'])) {
            $data['user_id'] = $data['employee_id'];
            // 获取用户所在部门
            $userDept = Db::name('user_department_relation')
                ->where('user_id', $data['user_id'])
                ->find();
            $data['department_id'] = $userDept ? $userDept['department_id'] : 1; // 默认部门ID为1
        }
        
        // 过滤掉不存在的字段
        $allowedFields = [
            'user_id', 'department_id', 'expense_type', 'amount', 'expense_date', 'status', 'remark', 'create_time'
        ];
        
        $filteredData = [];
        foreach ($allowedFields as $field) {
            if (isset($data[$field])) {
                $filteredData[$field] = $data[$field];
            }
        }
        
        // 确保必要字段存在
        if (!isset($filteredData['user_id'])) {
            return json(['code' => 400, 'msg' => 'user_id字段缺失']);
        }
        
        if (!isset($filteredData['department_id'])) {
            return json(['code' => 400, 'msg' => 'department_id字段缺失']);
        }
        
        // 设置创建时间
        $filteredData['create_time'] = date('Y-m-d H:i:s');
        
        // 记录处理后的数据
        file_put_contents(__DIR__ . '/log250825/expense_add.log', date('Y-m-d H:i:s') . ' - 添加费用报销: ' . json_encode($filteredData, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
        
        $id = Db::name('finance_expense')->insertGetId($filteredData);
        
        if ($id) {
            // 获取新增的费用报销记录
            $newExpense = Db::name('finance_expense')->where('id', $id)->find();
            
            // 关联用户信息
            $user = Db::name('user')->where('id', $newExpense['user_id'])->find();
            $department = Db::name('user_department')->where('id', $newExpense['department_id'])->find();
            $newExpense['employee_name'] = $user ? $user['realname'] : '';
            $newExpense['department_name'] = $department ? $department['name'] : '';
            $newExpense['employee_id'] = $newExpense['user_id']; // 添加employee_id字段
            
            return json(['code' => 200, 'msg' => '添加成功', 'data' => $newExpense]);
        } else {
            return json(['code' => 400, 'msg' => '添加失败']);
        }
    }
    
    /**
     * 更新费用报销
     */
    public function updateExpense()
    {
        $data = Request::post();
        
        $validate = Validate::rule([
            'id' => 'require|number',
            'employee_id' => 'require|number',
            'expense_type' => 'require',
            'amount' => 'require|float',
            'expense_date' => 'require|date',
            'status' => 'require|number',
        ]);
        
        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }
        
        // 将employee_id映射到user_id
        if (isset($data['employee_id'])) {
            $data['user_id'] = $data['employee_id'];
            // 获取用户所在部门
            $userDept = Db::name('user_department_relation')
                ->where('user_id', $data['user_id'])
                ->find();
            $data['department_id'] = $userDept ? $userDept['department_id'] : 1; // 默认部门ID为1
        }
        
        // 过滤掉不存在的字段
        $allowedFields = [
            'id', 'user_id', 'department_id', 'expense_type', 'amount', 'expense_date', 'status', 'remark', 'update_time'
        ];
        
        $filteredData = [];
        foreach ($allowedFields as $field) {
            if (isset($data[$field])) {
                $filteredData[$field] = $data[$field];
            }
        }
        
        $filteredData['update_time'] = date('Y-m-d H:i:s');
        
        // 记录日志
        file_put_contents(__DIR__ . '/log250825/expense_update.log', date('Y-m-d H:i:s') . ' - 更新费用报销: ' . json_encode($filteredData, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
        
        $result = Db::name('finance_expense')->update($filteredData);
        
        if ($result !== false) {
            // 获取更新后的费用报销记录
            $updatedExpense = Db::name('finance_expense')->where('id', $filteredData['id'])->find();
            
            // 关联用户信息
            $user = Db::name('user')->where('id', $updatedExpense['user_id'])->find();
            $department = Db::name('user_department')->where('id', $updatedExpense['department_id'])->find();
            $updatedExpense['employee_name'] = $user ? $user['realname'] : '';
            $updatedExpense['department_name'] = $department ? $department['name'] : '';
            
            return json(['code' => 200, 'msg' => '更新成功', 'data' => $updatedExpense]);
        } else {
            return json(['code' => 400, 'msg' => '更新失败']);
        }
    }
    
    /**
     * 删除费用报销
     */
    public function deleteExpense()
    {
        $id = Request::param('id');
        $ids = Request::param('ids');
        
        if (empty($id) && empty($ids)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        // 记录日志
        file_put_contents(__DIR__ . '/log250825/expense_delete.log', date('Y-m-d H:i:s') . ' - 删除费用报销: ' . json_encode([
            'id' => $id,
            'ids' => $ids
        ], JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
        
        // 批量删除
        if (!empty($ids)) {
            // 如果ids是字符串，将其转换为数组
            if (is_string($ids)) {
                $ids = explode(',', $ids);
            }
            
            $result = Db::name('finance_expense')->delete($ids);
        } else {
            // 单个删除
            $result = Db::name('finance_expense')->delete($id);
        }
        
        if ($result) {
            return json(['code' => 200, 'msg' => '删除成功']);
        } else {
            return json(['code' => 400, 'msg' => '删除失败']);
        }
    }
    
    /**
     * 获取财务统计数据
     */
    public function getFinancialStatistics()
    {
        // 获取查询日期范围
        $startDate = Request::param('startDate', date('Y-m-01'));
        $endDate = Request::param('endDate', date('Y-m-t'));
        
        // 剩余应收款项总额（未结清的）
        $totalReceivable = Db::name('finance_receivable')
            ->where('status', '<>', 2) // 未结清的
            ->sum('amount');
            
        // 历史应收款项总额（所有的）
        $historyReceivable = Db::name('finance_receivable')
            ->sum('amount');
            
        // 剩余应付款项总额（未结清的）
        $totalPayable = Db::name('finance_payable')
            ->where('status', '<>', 2) // 未结清的
            ->sum('amount');
            
        // 历史应付款项总额（所有的）
        $historyPayable = Db::name('finance_payable')
            ->sum('amount');
            
        // 本期收入总额（查询日期范围内已确认的收款）
        $totalIncome = Db::name('finance_receipt')
            ->where('receipt_date', '>=', $startDate)
            ->where('receipt_date', '<=', $endDate)
            ->where('status', '=', 2) // 已确认的
            ->sum('amount');
            
        // 累计收入总额（所有已确认的收款）
        $historyIncome = Db::name('finance_receipt')
            ->where('status', '=', 2) // 已确认的
            ->sum('amount');
            
        // 本期支出总额（查询日期范围内已确认的付款和报销）
        $totalExpense = Db::name('finance_payment')
            ->where('payment_date', '>=', $startDate)
            ->where('payment_date', '<=', $endDate)
            ->where('status', '=', 2) // 已确认的
            ->sum('amount');
            
        $totalExpense += Db::name('finance_expense')
            ->where('expense_date', '>=', $startDate)
            ->where('expense_date', '<=', $endDate)
            ->where('status', '=', 3) // 已报销的
            ->sum('amount');
            
        // 累计支出总额（所有已确认的付款和报销）
        $historyExpense = Db::name('finance_payment')
            ->where('status', '=', 2) // 已确认的
            ->sum('amount');
            
        $historyExpense += Db::name('finance_expense')
            ->where('status', '=', 3) // 已报销的
            ->sum('amount');
        
        // 获取收入明细列表
        $incomeList = Db::name('finance_receipt')
            ->where('receipt_date', '>=', $startDate)
            ->where('receipt_date', '<=', $endDate)
            ->where('status', '=', 2) // 已确认的
            ->order('receipt_date', 'desc')
            ->limit(10)
            ->select()
            ->toArray();
            
        // 关联客户信息
        foreach ($incomeList as &$item) {
            $customer = Db::name('customer')->where('id', $item['customer_id'])->find();
            $item['customer_name'] = $customer ? $customer['customer_name'] : '';
        }
        
        // 获取支出明细列表
        $expenseList = Db::name('finance_payment')
            ->where('payment_date', '>=', $startDate)
            ->where('payment_date', '<=', $endDate)
            ->where('status', '=', 2) // 已确认的
            ->order('payment_date', 'desc')
            ->limit(10)
            ->select()
            ->toArray();
            
        // 关联供应商信息
        foreach ($expenseList as &$item) {
            $supplier = Db::name('supplier')->where('id', $item['supplier_id'])->find();
            $item['supplier_name'] = $supplier ? $supplier['supplier_name'] : '';
        }
        
        // 准备图表数据
        $chartData = [];
        
        // 获取日期范围内的所有日期
        $dates = [];
        $incomeData = [];
        $expenseData = [];
        
        $currentDate = strtotime($startDate);
        $endTimestamp = strtotime($endDate);
        
        while ($currentDate <= $endTimestamp) {
            $dateStr = date('Y-m-d', $currentDate);
            $dates[] = $dateStr;
            
            // 当日收入
            $dayIncome = Db::name('finance_receipt')
                ->where('receipt_date', '=', $dateStr)
                ->where('status', '=', 2)
                ->sum('amount');
            $incomeData[] = $dayIncome ?: 0;
            
            // 当日支出
            $dayExpense = Db::name('finance_payment')
                ->where('payment_date', '=', $dateStr)
                ->where('status', '=', 2)
                ->sum('amount');
                
            $dayExpense += Db::name('finance_expense')
                ->where('expense_date', '=', $dateStr)
                ->where('status', '=', 3)
                ->sum('amount');
                
            $expenseData[] = $dayExpense ?: 0;
            
            // 移动到下一天
            $currentDate = strtotime('+1 day', $currentDate);
        }
        
        $chartData = [
            'dates' => $dates,
            'incomeData' => $incomeData,
            'expenseData' => $expenseData
        ];
            
        return json([
            'code' => 200, 
            'msg' => '获取成功', 
            'data' => [
                'totalReceivable' => $totalReceivable ?: 0,
                'totalPayable' => $totalPayable ?: 0,
                'totalIncome' => $totalIncome ?: 0,
                'totalExpense' => $totalExpense ?: 0,
                'historyReceivable' => $historyReceivable ?: 0,
                'historyPayable' => $historyPayable ?: 0,
                'historyIncome' => $historyIncome ?: 0,
                'historyExpense' => $historyExpense ?: 0,
                'incomeList' => $incomeList,
                'expenseList' => $expenseList,
                'chartData' => $chartData
            ]
        ]);
    }

    /**
     * 获取应收款项详情
     */
    public function getReceivableDetail()
    {
        $id = Request::param('id');
        
        if (empty($id)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        $detail = Db::name('finance_receivable')->where('id', $id)->find();
        
        if (!$detail) {
            return json(['code' => 404, 'msg' => '记录不存在']);
        }
        
        // 关联客户信息
        $customer = Db::name('customer')->where('id', $detail['customer_id'])->find();
        $detail['customer_name'] = $customer ? $customer['customer_name'] : '';
        
        return json(['code' => 200, 'msg' => '获取成功', 'data' => $detail]);
    }

    /**
     * 获取收款单详情
     */
    public function getReceiptDetail()
    {
        $id = Request::param('id');
        
        if (empty($id)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        $receipt = Db::name('finance_receipt')->where('id', $id)->find();
        
        if (!$receipt) {
            return json(['code' => 404, 'msg' => '收款单不存在']);
        }
        
        // 关联客户信息
        $customer = Db::name('customer')->where('id', $receipt['customer_id'])->find();
        $receipt['customer_name'] = $customer ? $customer['customer_name'] : '';
        
        return json(['code' => 200, 'msg' => '获取成功', 'data' => $receipt]);
    }

    /**
     * 获取付款单详情
     */
    public function getPaymentDetail()
    {
        $id = Request::param('id');
        
        if (empty($id)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        $payment = Db::name('finance_payment')->where('id', $id)->find();
        
        if (!$payment) {
            return json(['code' => 404, 'msg' => '付款单不存在']);
        }
        
        // 关联供应商信息
        $supplier = Db::name('supplier')->where('id', $payment['supplier_id'])->find();
        $payment['supplier_name'] = $supplier ? $supplier['supplier_name'] : '';
        
        return json(['code' => 200, 'msg' => '获取成功', 'data' => $payment]);
    }

    /**
     * 获取费用报销详情
     */
    public function getExpenseDetail()
    {
        $id = Request::param('id');
        
        if (empty($id)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        $detail = Db::name('finance_expense')->where('id', $id)->find();
        
        if (!$detail) {
            return json(['code' => 400, 'msg' => '记录不存在']);
        }
        
        // 关联用户和部门信息
        $user = Db::name('user')->where('id', $detail['user_id'])->find();
        $department = Db::name('user_department')->where('id', $detail['department_id'])->find();
        $detail['employee_name'] = $user ? $user['realname'] : '';
        $detail['department_name'] = $department ? $department['name'] : '';
        
        // 将user_id映射为employee_id（前端需要）
        $detail['employee_id'] = $detail['user_id'];
        
        return json(['code' => 200, 'msg' => '获取成功', 'data' => $detail]);
    }

    /**
     * 获取应付款项详情
     */
    public function getPayableDetail()
    {
        $id = Request::param('id');
        
        if (empty($id)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        $detail = Db::name('finance_payable')->where('id', $id)->find();
        
        if (!$detail) {
            return json(['code' => 404, 'msg' => '记录不存在']);
        }
        
        // 关联供应商信息
        $supplier = Db::name('supplier')->where('id', $detail['supplier_id'])->find();
        $detail['supplier_name'] = $supplier ? $supplier['supplier_name'] : '';
        
        return json(['code' => 200, 'msg' => '获取成功', 'data' => $detail]);
    }
}